package network;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.nio.ByteBuffer;

public class Packet_Message extends Packet 
{
	public enum MessageType{HANDSHAKE,ACKNOWLEDGEMENT,TEXT};
	public String m_string;
	public byte [] m_data;
	public MessageType m_msgtype;
	public Packet_Message(String string,int timestamp, MessageType msgtype)
	{
		m_type=packettype.MESSAGE;
		m_string=string;	
		m_timestamp=timestamp;
		m_msgtype=msgtype;
	}
	
	public Packet_Message(DatagramPacket pack)
	{
		ByteBuffer buffer=ByteBuffer.wrap(pack.getData());
		Header(pack.getAddress(),buffer);
		
		//now, need to read information
		m_msgtype=getMsgType(buffer.get());
		m_string=Packet.ReadString(buffer);
		byte l=buffer.get();
		if (l>0)
		{
			m_data=new byte[l];
			buffer.get(m_data, 0, l);
		}
	}
	
	MessageType getMsgType(byte value)
	{
		switch (value)
		{
		case 0:
			return MessageType.TEXT;

		case 1:
			return MessageType.ACKNOWLEDGEMENT;

		case 2:
			return MessageType.HANDSHAKE;
		
		}
		return MessageType.TEXT;
	}
	
	byte getbyteforType(MessageType type)
	{
		switch (type)
		{
		case HANDSHAKE:
			return 2;

			
		case ACKNOWLEDGEMENT:
			return 1;

			
		case TEXT:
			return 0;
	
		}
		return 0;
	}
	
	
	public DatagramPacket Encode(InetAddress address, int port)
	{
		byte []buffer=new byte[1024];
		ByteBuffer BB=ByteBuffer.wrap(buffer);
		//encode type
		BB.put(getTypebyte(m_type));
		BB.putInt(m_timestamp);
		//encode handle
		BB.put(getbyteforType(m_msgtype));
		Packet.WriteString(BB,m_string);
		if (m_data==null)
		{
			BB.put((byte) 0);
		}
		else
		{
			BB.put((byte) m_data.length);
			BB.put(m_data);
			
		}
		return new DatagramPacket(buffer,buffer.length,address,port);
	}	
}
